package com.ffzx.parentweb.interceptor;


import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jasig.cas.client.util.AssertionHolder;
import org.jasig.cas.client.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.dubbo.config.spring.ReferenceBean;
import com.alibaba.dubbo.rpc.service.GenericService;
import com.ffzx.commerce.framework.dto.ResultDto;
import com.ffzx.commerce.framework.system.entity.SysUser;
import com.ffzx.commerce.framework.utils.ConfigUtil;
import com.ffzx.commerce.framework.utils.JsonMapper;
import com.ffzx.commerce.framework.utils.RedisWebUtils;
import com.ffzx.commerce.framework.utils.SingletonDubboApplication;
import com.ffzx.commerce.framework.utils.StringUtil;
import com.ffzx.commerce.framework.utils.WebUtils;
import com.ffzx.parentweb.utils.PermisstionUtil;

/**
 * 登录验证拦截器
 * @author zhugj
 * @date 2016年1月16日 下午3:28:42
 * @version 1.0
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
	
	private final static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
	
	@Autowired
	private PermisstionUtil permisstionUtil;

	private GenericService sysUserApiService;
	
	{
		ReferenceBean<GenericService> referenceConfig = new ReferenceBean<GenericService>();
		referenceConfig.setInterface("com.ffzx.permission.api.service.SysUserApiService");
		referenceConfig.setGeneric(Boolean.TRUE);
		referenceConfig.setVersion("1.0");
		referenceConfig.setId("sysUserApiService");
		SingletonDubboApplication.getInstance().destroyBean(referenceConfig.getId());
		SingletonDubboApplication.getInstance().addReferenceBean(referenceConfig.getId(), referenceConfig);
		sysUserApiService = (GenericService) SingletonDubboApplication.getInstance().getReferenceObject(referenceConfig.getId());
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		Assertion assertion = AssertionHolder.getAssertion();

		// 实际cas-client-core中org.jasig.cas.client.authentication.AuthenticationFilter已经进行了单点登录认证，这里主要是为了获得用户信息
		if (assertion == null || assertion.getPrincipal() == null
				|| assertion.getPrincipal().getName() == null) {
			//logger.info("current user:" +RedisWebUtils.getLoginUser() != null ? RedisWebUtils.getLoginUser().getLoginName() : " " +" have not login in ");
			// 没有登录，跳转到没有登录页面
			response.sendRedirect(ConfigUtil.getInstance().getCasServerUrl());
			return false;
		}

		//从redis取,如果redis为空,从db中取,取了之后更新redis
	    SysUser currentUser = RedisWebUtils.getLoginUser();
	    if (currentUser == null) {
	    	
	    	Map<?, ?> genericResult = (Map<?, ?>) sysUserApiService.$invoke("getUserByName", new String[] { "java.lang.String" }, new Object[] { assertion.getPrincipal().getName() });
			ResultDto resultDto = new ResultDto();
			resultDto.setCode((String)genericResult.get("code"));
			resultDto.setMessage((String)genericResult.get("message"));
			resultDto.setData(genericResult.get("data"));
	    	
	    	currentUser = (SysUser)JsonMapper.getInstance().fromJson((String)resultDto.getData(), SysUser.class);
	    	//保存数据Redis
	    	RedisWebUtils.setLoginUser(currentUser);
			
			//初始化权限
	    	permisstionUtil.initPermission(currentUser.getId());
	    }
	    
	    //判断是否有权限   add by cmm 2016-8-8
	    Set<String> permissionSet = RedisWebUtils.getPermission();
	    if(null == permissionSet){
	    	//初始化权限
	    	permisstionUtil.initPermission(currentUser.getId());
	    }
	    
	    Object basePathObj = request.getSession().getAttribute("BasePath");
		String basePath = basePathObj == null ? "" : (String)basePathObj;
		if (StringUtil.isBlank(basePath)) {
			WebUtils.setBasePath(request, System.getProperty("web.basepath"));
		}
	    
		return super.preHandle(request, response, handler);
	}
}